/**
 * 封装文件下载
 * @param data
 * @param fileUrl
 * application/x-www-form-urlencoded
 */

export function fileDownload (data, fileUrl) {
  let _that = this;
  // let type = data.type
  // if (type.includes('application/json')) {
  let reader = new FileReader();
  reader.onload = function (event) {
    let content = reader.result;
    try {
      // 普通对象数据，后台抛出异常
      let message = JSON.parse(content) ;// 错误信息
      // TODO 错误处理
      if (message.code !== '200') {
        _that.$message.error(message.msg);
        return;
      }
    } catch (err) {
      // 解析成对象失败，是正常的文件流
      if (fileUrl.indexOf('.') >= 0) {
        let timestamp = new Date().getTime();
        let str = fileUrl.split('?');
        var fileName = '';
        if (str.length === 1) {
          fileUrl = str[0];
          fileName =
            timestamp + '.' + fileUrl.split('.')[fileUrl.split('.').length - 1];
        } else if (str.length === 2) {
          fileName = fileUrl.split('=')[1];
        }
        download(data, fileName);
      } else {
        _that.$message.info('文件路径有误，下载失败!');
        // return
      }
    }
  };
  reader.readAsText(data);
  return true;
}

function download (data, fileName) {
  if ('download' in document.createElement('a')) {
    // 非IE下载
    const elink = document.createElement('a');
    elink.download = fileName;
    elink.style.display = 'none';
    elink.href = URL.createObjectURL(data);
    document.body.appendChild(elink);
    elink.click();
    URL.revokeObjectURL(elink.href); // 释放URL 对象
    document.body.removeChild(elink);
  } else {
    // IE10+下载
    navigator.msSaveBlob(data, fileName);
  }
}
